<template>
  <div class="scene-company-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <template v-for="(item, index) in formList">
        <el-form-item
          v-if="!popConfig.disabled || item.prop !== 'sceneInfo' && popConfig.disabled"
          :key="`${item.prop}${index}`"
          :style="item.itemStyle || {}"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass">
          <component
            :is="item.componentType || 'el-input'"
            v-model="formData[item.prop]"
            :clearable="true"
            :class="item.class"
            :props="item.props"
            :options="item.options"
            v-bind="item.attrConfig || {}"
            @change="handlerSelectData(item)">
            <template v-for="option in item.optionList">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
          </component>
        </el-form-item>
      </template>
      <div v-if="!tableTitle.hidden" class="div-width">
        <el-form-item :label="tableTitle.name"></el-form-item>
      </div>
      <div class="table-div">
        <el-table class="area-table-border" max-height="300" v-if="!isAdd" :data="sceneList">
          <el-table-column
            v-for="column in columnList"
            :prop="column.prop"
            :label="column.label"
            :width="column.width">
          </el-table-column>
          <el-table-column v-if="!popConfig.disabled" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="danger" size="small" @click="removeRoom(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
  </div>
</template>

<script>
import { dictMixin } from '@/mixin/dict'
import { parseAareToObj, parseSceneData } from '@/utils/scene-data'
import api from '@/api/apis/sceneRoom'

export default {
  name: 'AddSceneCompany',
  mixins: [dictMixin],
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isAdd: true,
      formData: {
        cancelRoomIds: []
      },
      formList: [
        {
          name: '公司id',
          prop: 'id',
          attrConfig: {
            disabled: true
          }
        }, {
          name: '公司名称',
          prop: 'companyName',
          attrConfig: { placeholder: '请输入公司名称' }
        },
        {
          name: '所属项目',
          prop: 'sceneProjectId',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'commonSelected',
          selectParams: {
            code: 'SceneProjectSelected'
          },
          attrConfig: {
            placeholder: '请选择所属项目',
            options: []
          },
          dataProp: {
            dataType: 'resData',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        },
        {
          name: '新增空间',
          prop: 'sceneInfo',
          componentType: 'el-cascader',
          attrConfig: {
            placeholder: '请选择所属场景'
          },
          options: [],
          props: { multiple: true }
        },
        {
          name: '建筑面积(m²)',
          prop: 'companyArea',
          attrConfig: {
            placeholder: '建筑面积(m²)',
            disabled: true
          }
        }
      ],
      tableTitle: {
        name: '',
        hidden: true
      },
      areaData: {},
      sceneList: [],
      // 编辑框空间列表的表头配置
      columnList: [
        {
          prop: 'edificeName',
          label: '楼栋名称'
        }, {
          prop: 'floorName',
          label: '楼层名称'
        }, {
          prop: 'roomName',
          label: '空间名称'
        }, {
          prop: 'roomArea',
          label: '空间建筑面积(㎡)'
        }
      ]
    }
  },
  computed: {
    rules() {
      return {
        sceneProjectId: [{ required: true, message: '请选择所属项目', trigger: 'blur' }],
        sceneInfo: [{ required: true, message: '请选择新增空间', trigger: 'blur', validator: this.sceneInfoValidator }],
        companyName: [
          { required: true, message: '公司名称必填', trigger: 'blur' },
          { max: 100, message: '公司名称最多100字符', trigger: 'blur' }
        ]
        // value: [{ required: true, message: '请输入值', trigger: 'blur' }]
      }
    }
  },
  watch: {
    popConfig: {
      handler(data) {
        if (data.disabled) {
          this.formList.forEach((e) => {
            e.attrConfig.disabled = true
          })
        }
        this.tableTitle.name = data.disabled ? '公司场景详情：' : '已有空间：'
      },
      deep: true,
      immediate: true
    },
    popData: {
      handler(data) {
        this.isAdd = !data.id
        this.formList.forEach((e) => {
          if (data[e.prop] != null) {
            this.$set(this.formData, e.prop, data[e.prop])
          }
        })
        this.$set(this.formData, 'id', data.id)
        if (data.sceneProjectId) {
          // 查询场景选择的数据
          this.getRoomList(data.sceneProjectId)
        }
        if (data.id) {
          // 查询选中的数据
          this.getCompanyRoomList(data.id)
          // this.formList[4].hidden = false
          this.tableTitle.hidden = false
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...(this.formData || {})
      }
      const roomIds = params.sceneInfo ? params.sceneInfo.map(item => item[2]) : []
      delete params.sceneInfo
      params.roomIds = roomIds
      this.submit(params)
    }
  },
  methods: {
    sceneInfoValidator(rule, value, callback) {
      if (this.formData.sceneInfo?.length > 0) {
        callback()
      } else {
        callback(rule.message)
      }
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }

      if (config.prop === 'sceneProjectId') {
        // 选择项目后加载场景数据
        this.getRoomList(this.formData[config.prop])
      } else if (config.prop === 'sceneInfo') {
        // 选择场景时计算面积
        this.resetArea()
      }
    },
    /**
     * 重新计算空间面积
     */
    resetArea() {
      // 已绑定的空间面积
      const totalRoomArea = this.sceneList.reduce((total, item) => {
        return total + item.roomArea
      }, 0)
      // 选择的新增空间面积
      let selArea = 0
      if (this.formData.sceneInfo) {
        const roomIds = this.formData.sceneInfo.map(item => item[2]).filter(item => item != null)
        selArea = roomIds.reduce((total, roomId) => {
          return total + this.areaData[roomId]
        }, 0)
      }
      this.formData.companyArea = totalRoomArea + selArea
    },
    /**
     * 删除关联场景
     */
    removeRoom(index) {
      this.formData.cancelRoomIds.push(this.sceneList[index].id)
      this.sceneList.splice(index, 1)
      this.resetArea()
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const res = await this.$api.sceneCompany[this.isAdd ? 'add' : 'update'](params)
          if (Number(res.code) === 1000) {
            this.$message.success(`${this.isAdd ? '新增' : '编辑'}成功！`)
            this.$emit('onFinish', 'scene-company-add')
          } else if (res.msg) {
            this.$message({ type: 'error', message: res.msg })
          }
        }
      })
    },
    /**
     * 获取空间列表
     * @param sceneProjectId
     */
    async getRoomList(sceneProjectId) {
      let res = await api.queryRoomList({
        sceneProjectId,
        sortColumn: 'floorName',
        sortOrder: 'asc'
      })
      // 解析面积数据，方便计算
      this.areaData = parseAareToObj(res.data)
      const roomList = parseSceneData(res.data)
      let item = this.formList[3]
      item.options = roomList
      this.$set(this.formList, 3, { ...item })
    },
    /**
     * 获取公司绑定的空间列表
     * @param sceneCompanyId
     */
    async getCompanyRoomList(sceneCompanyId) {
      let res = await api.queryRoomList({ sceneCompanyId })
      this.sceneList = res.data
      // const sceneInfo = []
      // this.sceneList.forEach(item => {
      //   const sceneItem = []
      //   if (item.sceneEdificeId != null) {
      //     sceneItem.push(item.sceneEdificeId)
      //   }
      //   if (item.sceneFloorId != null) {
      //     sceneItem.push(item.sceneFloorId)
      //   }
      //   if (item.id != null) {
      //     sceneItem.push(item.id)
      //   }
      //   sceneInfo.push(sceneItem)
      // })
      // this.formData.sceneInfo = sceneInfo
    }
  }
}
</script>

<style lang="scss" scoped>
.scene-company-box {
  color: #333;
  padding: 0 20px;

  ::v-deep .el-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .el-form-item {
      width: calc(50% - 10px);

      &.width100p {
        width: 100%;
      }

      .el-form-item__label {
        color: #666;
        font-size: 14px;
      }

      &.form-sub-title {
        width: 100%;

        .el-form-item__label {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          font-weight: bold;
          color: #333;
          font-size: 16px;
          line-height: 1;

          &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 15px;
            background-color: #00858d;
            margin-right: 5px;
          }
        }
      }
    }

    .div-width {
      width: 100%;
    }

    .table-div {
      width: 100%;
      padding-left: 30px;

      .area-table-border .el-table {
        width: 80%;
        border: 1px solid #ccc;
      }

      .el-table__header tr, .el-table__header th {
        background-color: #f2f4f5;
        color: #333;
      }
    }

    .el-select,
    .el-cascader {
      width: 100%;
    }
  }
}
</style>
